package cn.uway.config;

import javax.sql.DataSource;

import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;

/**
 * mybatis数据源、连接池、事务管理器 配置
 * 
 * @author pengcc
 *
 */
@Configuration
@MapperScan(basePackages="cn.uway.dao")
public class MyBatisConfig {

	/*
	@Bean  
    @ConfigurationProperties(prefix = "spring.datasource")  
    public PooledDataSource dataSource() {  
		PooledDataSource pooledDs = new PooledDataSource();  
        return pooledDs;  
    }
    */  
	
	@Bean  
    @ConfigurationProperties(prefix = "spring.datasource")  
    public DruidDataSource  dataSource() {  
		 DruidDataSource druidDataSource = new DruidDataSource();  
	     return druidDataSource;  
    }  
	
	
	@Bean
	public SqlSessionFactory sqlSessionFactory(DataSource ds) throws Exception{
         SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
         sqlSessionFactoryBean.setDataSource(dataSource());
         PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
         sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mybatis/*.xml"));
         return sqlSessionFactoryBean.getObject();
	}
	
	@Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean
    public PlatformTransactionManager  transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }    
	
}
